package com.youdianstar.app.util

import android.app.Activity
import android.app.Dialog
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.youdianstar.app.R
import com.youdianstar.app.support.paging.ICardEditListener
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.util.*
import com.youdianstar.app.common.util.dialog.DialogUtil
import com.youdianstar.app.common.widget.*
import com.youdianstar.app.adapter.CouponSelectAdapter
import com.youdianstar.app.adapter.InvitePlanAdapter
import com.youdianstar.app.entity.*


/**
 * File: WalletDialogUtil
 * Author: 82149 Create: 2021/11/25 17:10
 * Changes (from 2021/11/25)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class WalletDialogUtil : DialogUtil() {
    companion object {

        val instance by lazy { WalletDialogUtil() }

    }

    /**
     * 租借流程-支付授权选择
     *
     * @param googleReady Google pay state
     * @param lastPayType 上次选择的类型 1.谷歌 2.已绑卡 3.新卡 4.预付款
     */
    fun showPreAuthorizationSheet(mContext: Activity,
                                  googleReady: Boolean, lastPayType: Int, prepaymentAmount: Double,
        cardInfo: CardEntity?= null,
        googlePayAction: (() -> Unit) = { },
        bankcardAction: (() -> Unit) = { },
        addCardAction: (() -> Unit) = { },
        depositAction: (() -> Unit) = { }
    ): Dialog? {
        val rootView: View = LayoutInflater.from(mContext).inflate(R.layout.sheet_pay_author_select, null)
        val dialog = helper?.createBaseDialog(mContext, R.style.AlertDialogStyle, true, rootView)
        val btnClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val btnRlGooglePay = rootView.findViewById<RelativeLayout>(R.id.btn_google)
        val btnBankcard = rootView.findViewById<TextView>(R.id.btn_bankcard)
        val btnDeposit = rootView.findViewById<TextView>(R.id.btn_deposit)
        val txOr = rootView.findViewById<TextView>(R.id.tx_or)
        val txPyaHint = rootView.findViewById<TextView>(R.id.tx_pay_hint)
        val clBankcard = rootView.findViewById<ConstraintLayout>(R.id.cl_bankcard)
        val btnShowAll = rootView.findViewById<TextView>(R.id.btn_show_all)
        val tvBankcard = rootView.findViewById<TextView>(R.id.tv_bankcard)

        val llGoogle = rootView.findViewById<LinearLayout>(R.id.ll_recent_google)
        val llBindCard = rootView.findViewById<LinearLayout>(R.id.ll_recent_bindCard)
        val llAuthor = rootView.findViewById<LinearLayout>(R.id.ll_recent_author)
        val llDeposit = rootView.findViewById<LinearLayout>(R.id.ll_recent_pre)

        when (lastPayType) {
            1 -> {
                llGoogle.visibility = View.VISIBLE
            }
            2 -> {
                txOr.visibility = View.GONE
                txPyaHint.visibility = View.GONE
                btnRlGooglePay.visibility = View.GONE
                if (cardInfo != null){
                    btnBankcard.visibility = View.GONE
                    clBankcard.visibility = View.VISIBLE
                    llAuthor.visibility = View.GONE
                    llBindCard.visibility = View.VISIBLE
                }else{
                    btnBankcard.visibility = View.VISIBLE
                    clBankcard.visibility = View.GONE
                    llAuthor.visibility = View.VISIBLE
                    llBindCard.visibility = View.GONE
                }
                btnDeposit.visibility = View.GONE
                btnShowAll.visibility = View.VISIBLE
            }
            3 -> {
                llBindCard.visibility = View.GONE
                clBankcard.visibility = View.GONE
                txOr.visibility = View.GONE
                txPyaHint.visibility = View.GONE
                btnRlGooglePay.visibility = View.GONE
                btnBankcard.visibility = View.VISIBLE
                btnDeposit.visibility = View.GONE
                llAuthor.visibility = View.VISIBLE
                btnShowAll.visibility = View.VISIBLE
            }
            4 -> {
                llDeposit.visibility = View.VISIBLE
            }
        }

        if (null!= cardInfo){
            tvBankcard.text = "**** **** **** "+cardInfo.bankNo
            clBankcard.visibility = View.VISIBLE
        }else{
            clBankcard.visibility = View.GONE
        }

        Tool.setUnderLine(mContext, btnShowAll, mContext.getString(R.string.rent_showAll), R.color.color_39404D)

        btnShowAll.setThrottleListener {
            btnShowAll.visibility = View.GONE
            btnRlGooglePay.visibility = View.VISIBLE
            btnBankcard.visibility = View.VISIBLE
        }
        btnClose.setThrottleListener {
            dialog?.dismiss()
        }
//        btnRlGooglePay.visibility = if (googleReady and !isCardPayLast) View.VISIBLE else View.GONE.
        btnRlGooglePay.isEnabled = googleReady
        btnRlGooglePay.setThrottleListener {
            if (!googleReady){
                return@setThrottleListener
            }
            googlePayAction.invoke()
        }
        btnBankcard.setThrottleListener {
            addCardAction.invoke()
        }
        btnDeposit.setThrottleListener {
            depositAction.invoke()
        }
        clBankcard.setThrottleListener {
            bankcardAction.invoke()
        }
        val syTx = DataAppManager.instance.symbolTx()
        val depositTx = syTx + MathUtil.round(prepaymentAmount)
        btnDeposit.text = String.format(mContext.getString(R.string.rent_continuePrepayment), depositTx)

        helper?.adjustSizeGravity(dialog, ScreenUtil.getScreenSize(mContext).x, 0, Gravity.BOTTOM)
        dialog?.show()
        return dialog
    }

    /**
     * 编辑卡信息
     *
     * @param context 上下文
     */
    fun showEditCardDialog(context: Activity, card: CardEntity, listener: ICardEditListener): Dialog? {
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.layout_card_edit, null)
        val dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val ivClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val tvTitle = rootView.findViewById<TextView>(R.id.set_title)
        val boxDefault = rootView.findViewById<CheckBox>(R.id.box_default)
        val ivDeleteRight = rootView.findViewById<ImageView>(R.id.iv_right)
        val tvDeleteDes = rootView.findViewById<TextView>(R.id.tv_item_remove)
        val clDeleteConform = rootView.findViewById<ConstraintLayout>(R.id.cl_remove_confirm)
        val tvCancel = rootView.findViewById<TextView>(R.id.tv_cancel)
        val tvRemove = rootView.findViewById<TextView>(R.id.tv_remove)
        listener.registerLayout(clDeleteConform, ivDeleteRight, boxDefault)
        //设置默认状态 删除布局收起
        ivDeleteRight.rotation = -90F
        clDeleteConform.visibility = View.GONE
        listener.onCardStateDefault(card.defaulted)
        tvTitle.text = card.bankName
        //设置事件监听
        ivClose.setOnClickListener {
            listener.cleanLayout()
            dialog?.dismiss()
        }
        boxDefault.setBackgroundResource(R.drawable.selector_box_gou)
        boxDefault.setOnCheckedChangeListener { buttonView, isChecked ->
            listener.onRequestCardDefault(isChecked, cardId = card.id)
        }
        tvDeleteDes.setThrottleListener {
            listener.onClickDeleteLayout()
        }
        ivDeleteRight.setThrottleListener {
            listener.onClickDeleteLayout()
        }
        tvCancel.setOnClickListener {
            listener.onClickDeleteLayout()
        }
        tvRemove.setOnClickListener {
            listener.cleanLayout()
            listener.onDeleteAction(card.id)
            dialog?.dismiss()
        }

        helper?.adjustSizeGravity(dialog, (ScreenUtil.getScreenSize(context).x * 0.96).toInt(), 0, Gravity.CENTER)
        dialog?.show()
        return dialog
    }


    /**
     * 支付页面--押金信息 (弃用)
     *
     * @param context
     */
    fun showDepositSheet(context: Activity, title: String? = null, content: String? = null, closeAction: (() -> Unit) = { }): Dialog? {

        val rootView: View = LayoutInflater.from(context).inflate(R.layout.sheet_report_loss, null)
        val dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val ivClose = rootView.findViewById<ImageView>(R.id.ic_cancel)
        ivClose.setOnClickListener {
            dialog?.dismiss()
            closeAction.invoke()
        }
        val tvTitle = rootView.findViewById<TextView>(R.id.details_title)
        val tvContent = rootView.findViewById<TextView>(R.id.tv_detail_content)
        title?.let {
            tvTitle.text = it
        }
        content?.let {
            tvContent.text = it
        }

        helper?.adjustSizeGravity(dialog, ScreenUtil.getScreenSize(context).x, ScreenUtil.getScreenSize(context).y, Gravity.CENTER)
        dialog?.show()
        return dialog
    }

    /**
     * 支付页面选择优惠券
     *
     * @param data Coupon list
     */
    fun showCouponSelectSheet(context: Activity, data: List<CouponRes>, defaultP: Int = -1,
                              selectAction: ((Int) -> Unit) = { }): Dialog? {
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.sheet_pay_coupon_select, null)
        val dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val ivClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val rcyList = rootView.findViewById<RecyclerView>(R.id.rcy_coupon)
        val btnConfirm = rootView.findViewById<Button>(R.id.btn_confirm)
        val clEmptyHolder = rootView.findViewById<ConstraintLayout>(R.id.cl_empty_holder)
        rcyList.layoutManager = LinearLayoutManager(context)
        var selectIndex = 0
        val adapter = CouponSelectAdapter(context = context, dataList = data, SheetCheckHelper(object : CheckHelper.HandleStateChange {
            override fun stateChange(holder: RecyclerView.ViewHolder, check: Boolean) {
                if (holder is CouponSelectAdapter.SheetHolder) {
                    holder.tvUse.visibility = if (check) View.INVISIBLE else View.VISIBLE
                    holder.ivSelect.visibility = if (check) View.VISIBLE else View.GONE
                    holder.rlSelected.setBackgroundResource(if (check) R.drawable.bg_shape_selected else R.drawable.bg_shape_redeem)
                }
            }

            override fun clickWhich(position: Int) {
                selectIndex = position
                selectAction(selectIndex)
            }
        }, rcyList, defaultP))
        rcyList.adapter = adapter
        clEmptyHolder.visibility = if (data.isEmpty()) View.VISIBLE else View.GONE
        ivClose.setThrottleListener {
            dialog?.dismiss()
        }
        btnConfirm.setThrottleListener {
            dialog?.dismiss()
        }

        helper?.adjustSizeGravity(dialog, ScreenUtil.getScreenSize(context).x, ScreenUtil.getScreenSize(context).y, Gravity.BOTTOM)
        dialog?.show()

        return dialog
    }

    /**
     * 支付结果页面 -- 收据弹框
     *
     * @param context
     */
    fun showReceiptDialog(context: Activity, emailStr: String, closeAction: ((String) -> Unit) = { }): Dialog? {
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.layout_receipt_send, null)
        val dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val edtEmail = rootView.findViewById<SearchEditText>(R.id.edit_email)
        val btnCancel = rootView.findViewById<TextView>(R.id.tv_Left)
        val btnSend = rootView.findViewById<TextView>(R.id.tv_Right)
        if (!StrUtil.isEmpty(emailStr)) {
            edtEmail.setText(emailStr)
        }
        btnCancel.setThrottleListener {
            dialog?.dismiss()
        }
        btnSend.setThrottleListener {
            val emailText = edtEmail.text.toString()
            if (StrUtil.isEmpty(emailText)) {
                ToastUtil.show(context, context.getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }
            if (!StrUtil.emailFormat(emailText.trim())) {
                ToastUtil.show(context, context.getString(R.string.toast_validEmail))
                return@setThrottleListener
            }
            closeAction.invoke(emailText.trim())
            dialog?.dismiss()
        }

        helper?.adjustSizeGravity(dialog, (ScreenUtil.getScreenSize(context).x * 0.96).toInt(), 0, Gravity.CENTER)
        dialog?.show()
        return dialog
    }



    /*************************************Reward 弹框*************************************/

    /**
     * 优惠券兑换--兑换积分优惠券提示
     *
     * @param balance 余额/积分
     * @param couponRed 兑换优惠券数据
     */
    fun sheetRedeemPoints(mContext: Activity, balance: Int, couponRed: CouponInfo?, redeemAction: ((String) -> Unit) = { }): Dialog? {
        val rootView: View = LayoutInflater.from(mContext).inflate(R.layout.sheet_redeem_point_c, null)
        val dialog = helper?.createBaseDialog(mContext, R.style.AlertDialogStyle, false, rootView)
        val ivClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val tvCpTitle = rootView.findViewById<TextView>(R.id.coupon_tv_title)
        val tvCpDate = rootView.findViewById<TextView>(R.id.coupon_tv_date)
        val tvCpAddress = rootView.findViewById<TextView>(R.id.coupon_tv_address)

        val tvPoints = rootView.findViewById<TextView>(R.id.tv_points)
        val btnConform = rootView.findViewById<Button>(R.id.btn_confirm)
        ivClose?.setThrottleListener {
            dialog?.dismiss()
        }
        val symbolStr = DataAppManager.instance.symbolTx()
        couponRed?.let { info ->
            //抵扣类型
            tvCpTitle?.text = if (null!=info.deduction) DataHelperEx.couponDeductTx(mContext,symbolStr,info.deduction) else "--"
            //有效期
            tvCpDate?.text = mContext.getString(R.string.order_expiryDate)+": "+DataHelperEx.checkCouponEndDate(info.exchangeEffectiveDays?:0)
            //使用范围
            tvCpAddress?.text = if (StrUtil.isEmpty(info.merchantNameList))
                mContext.getString(R.string.coupon_allStationUse)
            else
                info.merchantNameList

            tvPoints?.text = "${info.exchangePoint} "+mContext.getString(R.string.coupon_pts)
            btnConform.isEnabled = info.exchangePoint <= balance
            btnConform?.setThrottleListener {
                dialog?.dismiss()
                redeemAction.invoke(info.id.toString())
            }
        }

        helper?.adjustSizeGravity(dialog, ScreenUtil.getScreenSize(mContext).x, 0, Gravity.BOTTOM)
        dialog?.show()
        return dialog
    }


    /**
     * 优惠券兑换
     * --优惠码兑换优惠券结果提示(弃用)
     * @param result 优惠券数据
     */
    fun sheetRedeemPromoResult(context: Activity, result: RedeemResult,
                               redeemAction: ((String) -> Unit) = { }): Dialog? {
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.sheet_redeem_promo_res, null)
        val dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)

        val ivClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val clContainer = rootView.findViewById<ConstraintLayout>(R.id.cl_container_cou)
        val tvCpTitle = rootView.findViewById<TextView>(R.id.sheet_title)
        val tvCpDate = rootView.findViewById<TextView>(R.id.sheet_tv_date)
        val tvCpAddress = rootView.findViewById<TextView>(R.id.sheet_tv_address)
        val tvCpState = rootView.findViewById<TextView>(R.id.sheet_state)
        val tvCode = rootView.findViewById<TextView>(R.id.tv_code)
        val tvNotify = rootView.findViewById<TextView>(R.id.tx_notify)
        val btnDone = rootView.findViewById<Button>(R.id.btn_confirm)

        ivClose?.setThrottleListener {
            dialog?.dismiss()
        }
        btnDone?.setThrottleListener {
            dialog?.dismiss()
            redeemAction.invoke("Success")
        }

        clContainer?.visibility = if (null==result.userCoupon) View.GONE else View.VISIBLE
        result.userCoupon?.let {
            tvCpTitle?.text = it.title
            tvCpDate?.text = if (null == it.endTime) "" else DateUtil.getOrderDate(it.endTime)
            tvCpAddress?.text = if (StrUtil.isEmpty(it.merchantNameList)) context.getString(R.string.coupon_allStationUse) else it.merchantNameList
        }
        tvCode?.text = result.promoCode ?: ""

        helper?.adjustSizeGravity(dialog, ScreenUtil.getScreenSize(context).x, ScreenUtil.getScreenSize(context).y, Gravity.BOTTOM)
        dialog?.show()
        return dialog
    }


    /**
     * 邀请--邀请规则提示
     *
     * @param mContext 页面上下文
     * @param planList 邀请规则列表
     */
    fun sheetRedeemInvitationRule(mContext: Activity,planList:MutableList<InviteInfo>): Dialog?{
        val rootView: View = LayoutInflater.from(mContext).inflate(R.layout.sheet_redeem_invite, null)
        val mDialog = helper?.createBaseDialog(mContext, R.style.AlertDialogStyle, false, rootView)
        val ivClose = rootView.findViewById<ImageView>(R.id.iv_close)
        val tvSheetTitle = rootView.findViewById<TextView>(R.id.tv_title)
        val rcyPlan = rootView.findViewById<RecyclerView>(R.id.rcy_plans)
        val llEmpty = rootView.findViewById<ConstraintLayout>(R.id.cl_empty_holder)

        ivClose.setThrottleListener {
            mDialog?.dismiss()
        }
        if (planList.isEmpty()){
            llEmpty.visibility = View.VISIBLE
        }else{
            llEmpty.visibility = View.GONE
            rcyPlan.layoutManager = LinearLayoutManager(mContext)
            val mAdapter = InvitePlanAdapter(mContext, planList)
            rcyPlan.adapter = mAdapter
        }
        val heightV = (ScreenUtil.getScreenSize(mContext).y *0.65).toInt()
        helper?.adjustSizeGravity(mDialog, ScreenUtil.getScreenSize(mContext).x, heightV, Gravity.BOTTOM)
        mDialog?.show()

        return mDialog
    }
}